package com.duoduo.admin.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.duoduo.common.core.constant.CacheConstants;
import com.duoduo.common.jpa.service.CommonService;
import com.mason.duoduo.utils.ConvertUtils;
import com.duoduo.admin.api.dto.SysOauthClientDetailsDTO;
import com.duoduo.admin.entity.SysOauthClientDetails;
import com.duoduo.admin.repository.SysOauthClientDetailsRepository;

import jakarta.persistence.criteria.Predicate;

@Service
public class SysOauthClientDetailsService extends CommonService<SysOauthClientDetailsDTO, SysOauthClientDetails, String>{

	@Autowired
	private SysOauthClientDetailsRepository sysOauthClientDetailsRepository;

	@Override
	public Specification<SysOauthClientDetails> getWhere(final SysOauthClientDetailsDTO request) {
		return (root, query, cb) -> {
			final List<Predicate> predicate = new ArrayList<Predicate>();
			if(request.getClientId()!=null) {
				predicate.add(cb.equal(root.get("id"), request.getClientId()));	
			}		
			
			final Predicate[] pre = new Predicate[predicate.size()];
			return query.where(predicate.toArray(pre)).getRestriction();
		};
	}
	/**
	 * 通过ID删除客户端
	 * @param id
	 * @return
	 */
	@CacheEvict(value = CacheConstants.CLIENT_DETAILS_KEY, key = "#id")
	public void removeClientDetailsById(String id) {
		sysOauthClientDetailsRepository.deleteById(id);
	}
	/**
	 * 根据客户端信息
	 * @param clientDetails
	 * @return
	 */
	@CacheEvict(value = CacheConstants.CLIENT_DETAILS_KEY, key = "#clientDetails.clientId")
	public void updateClientDetailsById(SysOauthClientDetails clientDetails) {
		sysOauthClientDetailsRepository.save(clientDetails);
	}
	/**
	 * 清除客户端缓存
	 */
	@CacheEvict(value = CacheConstants.CLIENT_DETAILS_KEY, allEntries = true)
	public void clearClientCache() {

	}
	public List<SysOauthClientDetailsDTO> listClientDetails() {
		return sysOauthClientDetailsRepository.findAll().stream().map(p -> ConvertUtils.sourceToTarget(p, SysOauthClientDetailsDTO.class)).toList();
	}
}
